﻿using Permission.DataModel;
using Permission.Repository;
using Permission.UnitOfWork;
using Permission.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Permission.Service.Impl
{
    public class RoleService : IRoleService
    {
        private readonly IRoleRepository _roleRepository;

        private IUnitOfWork _unitOfWork;

        public RoleService(IRoleRepository roleRepository, IUnitOfWork unitOfWork)
        {
            _roleRepository = roleRepository;
            _unitOfWork = unitOfWork;
        }

        public Sys_Role LoadRole(string id)
        {
            return _roleRepository.Entities().FirstOrDefault(s => s.Id == id);
        }

        public object Roles()
        {
            return _roleRepository.Entities().Take(10).Select(a => new
                    {
                        a.Id,
                        a.RoleName,
                        a.RoleDesc,
                        a.CreateDate,
                        a.Status
                    }).ToList();

        }

        public List<Sys_Role> GetListRoleIdName()
        {
            return _roleRepository.Entities().ToList();
        }

        public ExecuteResult SaveRole(Sys_Role model)
        {
            ExecuteResult result = new ExecuteResult();
            try
            {
                if (string.IsNullOrEmpty(model.Id)) // 新增
                {
                    model.Id = Guid.NewGuid().ToString();
                    model.CreateDate = DateTime.Now;
                    _roleRepository.Insert(model);
                }
                else // 修改
                {
                    _roleRepository.Update(m => new Sys_Role
                    {
                        Id = model.Id,
                        RoleName = model.RoleName,
                        RoleDesc = model.RoleDesc,
                        Status = model.Status
                    });
                }
                result.Code = _unitOfWork.Commit() > 0 ? 0 : 1;
                return result;
            }
            catch (Exception)
            {
                result.Code = 1;
            }
            return result;
        }
    }
}
